package swagenda.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.log4j.Logger;

import swagenda.exception.NotInitializedException;


public class Preferences implements Serializable
{
	private static final long serialVersionUID = 20070911L;
	transient Logger logger = Logger.getLogger(this.getClass());
	
	public Person owner;
	transient static private final String filename = "swagenda.prefs";
	
	public boolean ready()
	{
		return (owner != null && owner.places != null && owner.places.size()>0);
	}
	
	public static File dir()
	{
		String sep = System.getProperty("file.separator");
		return new File(System.getProperty("user.home")+sep+".swagenda");
	}
	public static File file()
	{
		String sep = System.getProperty("file.separator");
		return new File(System.getProperty("user.home")+sep+".swagenda"+sep+filename);
	}
	
	public static Preferences load() throws NotInitializedException
	{
		Preferences prefs = null;
    	try
		{
    		if (!dir().exists())
    			dir().mkdir();

    		ObjectInputStream in = new ObjectInputStream(new FileInputStream(file()));
			prefs = (Preferences) in.readObject();
			in.close();
	   		return prefs;
		}
    	catch (Exception e)
    	{
    		// the file does not exist yet, must be created
    		throw new NotInitializedException();
    	}
	}
	
	public void save()
	{
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try
		{
			fos = new FileOutputStream(file());
			out = new ObjectOutputStream(fos);
			out.writeObject(this);
			out.close();
		}
		catch (IOException e)
		{
			logger.error("could not save preferences", e);
		}
	}
}
